package com.javacoo.fastdfs.client.internal.pool;

import org.apache.commons.pool2.BasePooledObjectFactory;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.impl.DefaultPooledObject;
import org.csource.fastdfs.StorageClient1;
import org.csource.fastdfs.TrackerClient;
import org.csource.fastdfs.TrackerServer;

import com.javacoo.fastdfs.client.api.pool.StorageClient1Wrapper;

import lombok.extern.slf4j.Slf4j;

/**
 * StorageClient1Wrapper工厂
 * @author: duanyong@jccfc.com
 * @since: 2020/4/30 11:03
 */
@Slf4j
public class StorageClient1WrapperFactory extends BasePooledObjectFactory<StorageClient1Wrapper> {
    /**
     *  创建一个新对象;当对象池中的对象个数不足时,将会使用此方法来"输出"一个新的"对象",并交付给对象池管理
     */
    @Override
    public StorageClient1Wrapper create() throws Exception {
        TrackerClient trackerClient = new TrackerClient();
        TrackerServer trackerServer = trackerClient.getConnection();
        StorageClient1 storageClient1 = new StorageClient1(trackerClient.getConnection(), null);
        log.info("StorageClient1WrapperFactory->create StorageClient1Wrapper");
        return StorageClient1Wrapper.builder().storageClient1(storageClient1).trackerServer(trackerServer).build();
    }

    @Override
    public PooledObject<StorageClient1Wrapper> wrap(StorageClient1Wrapper storageClient1Wrapper) {
        return new DefaultPooledObject<>(storageClient1Wrapper);
    }
    @Override
    public PooledObject<StorageClient1Wrapper> makeObject() throws Exception {
        return wrap(create());
    }
    @Override
    public void destroyObject(final PooledObject<StorageClient1Wrapper> p) throws Exception  {
        p.getObject().getTrackerServer().close();
        p.getObject().setStorageClient1(null);
        p.getObject().setTrackerServer(null);
        log.info("StorageClient1WrapperFactory->destroyObject->{}",p.getObject().hashCode());
    }
    @Override
    public boolean validateObject(final PooledObject<StorageClient1Wrapper> p) {
        try {
            boolean active = org.csource.fastdfs.ProtoCommon.activeTest(p.getObject().getTrackerServer().getSocket());
            // 检查链接是否可用
            //p.getObject().getStorageClient1().get_file_info("group1", "");
            log.info("StorageClient1WrapperFactory->validateObject->{},enabled->{}",p.getObject(),active);
            return active;
        } catch(Exception e){
            log.error("StorageClient1WrapperFactory->validateObject->{},enabled->{}",p.getObject(),false);
            return false;
        }
    }
}
